<template>
  <div class="container">
    <div class="card">
      <div class="img">
        <el-image
          v-if="course.cover !== null"
          :src="course.cover"
          class="image"
        >
          <template #error>
            <span>加载失败</span>
          </template>
        </el-image>
        <el-image
          v-else
          src="@/assets/image/course.png"
          class="image"
        />
      </div>
      <div class="content">
        <ul>
          <li>
            <h2>{{ course.name }}</h2>
            <p>
              <i>
                <el-icon><Postcard /></el-icon>
              </i>
              教师： <span>{{ $store.state.loginUser.nickName }}</span>
            </p>
          </li>
          <li>
            <p>
              <i>
                <el-icon><Management /></el-icon>
              </i>
              教学任务： <span>{{ total }}</span>
            </p>
          </li>
          <li>
            <p>
              <el-button type="primary" @click="details(course.id)">课程详情</el-button>
              <el-button type="warning" @click="uploadPhoto(course.id)">上传课程封面</el-button>
            </p>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <PhotoUploadDialog
    ref="photoUploadDialogRef"
    title="课程封面上传"
    :data="data"
    :autoUpload="false"
    @uploadSuccess="uploadSuccess"
  />
</template>

<script lang='ts' setup>
// 导入上传图像组件
import PhotoUploadDialog from '@/components/base/dialog/PhotoUploadDialog.vue';
import {
  defineProps, ref, getCurrentInstance, onMounted,
} from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import Request from '@/api/request/request';

// 接受父组件的值
interface Props {
  course: any
}
const { proxy } = getCurrentInstance();
const props = defineProps<Props>();
const router = useRouter();

const total = ref<number>(); // 当前课程下的教学任务数量
// 上传头像携带的参数，如本组件上传课程封面需要传递课程id，可以将课程id装到data，然后传到封装好的组件中
const data = ref();

// 跳转到课程信息，以及携带课程id
const details = (id: any) => {
  router.push({
    name: 'details',
  });
  sessionStorage.setItem('courseId', id);
};

// 获取当前课程下拥有多少个教学任务
const courseList = async () => {
  const resData:any = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOLTEACHINGTASK_MANAGE, null, {
    params: {
      courseId: props.course.id,
    },
  }).get();
  if (resData.success) {
    total.value = resData.data.totalRecords;
  }
};
onMounted(() => {
  courseList();
});

// 头像上传
const photoUploadDialogRef = ref();
// 当点击头像上传按钮时
const uploadPhoto = (courseId: number) => {
  // 设置头像上传地址
  let uploadImgUrl = proxy.$urls.API_URL_BACKSTAGE_SCHOOLCOURSERESOURCE_UPLOADCOURSECOVER_MANAGE;
  data.value = {
    courseId,
  };
  photoUploadDialogRef.value.openDialog(uploadImgUrl);
};
// 当头像上传成功
const uploadSuccess = () => {
  ElMessage({
    message: '上传成功',
    type: 'success',
  });
};
</script>

<style lang="scss" src="./Course.scss" scoped>

</style>
